package org.wheel.plugins.toolkit.sql.rule.plugin;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.StrUtil;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.JdbcNamedParameter;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.InExpression;
import net.sf.jsqlparser.expression.operators.relational.ParenthesedExpressionList;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.select.PlainSelect;
import org.wheel.plugins.toolkit.sql.helper.ColumnRef;
import org.wheel.plugins.toolkit.sql.plugin.RuleContext;
import org.wheel.plugins.toolkit.sql.plugin.RuleDataHolder;
import org.wheel.plugins.toolkit.sql.plugin.RulePlugin;

import java.util.Collection;

/**
 * 数据范围规则 – dept_id IN (:deptList)
 */
public class DataScopeRule implements RulePlugin {

    @Override
    public String name() {
        return "dataScope";
    }

    @Override
    public void apply(PlainSelect select, RuleContext ctx) {
        if(!RuleDataHolder.containsKey(this.name())){
            return;
        }
        Pair<ColumnRef, Collection<String>> dataPair = (Pair<ColumnRef, Collection<String>>) RuleDataHolder.get(this.name());

        String key = StrUtil.toCamelCase(dataPair.getKey().getColumn());

        InExpression in = new InExpression();
        in.setLeftExpression(new Column(dataPair.getKey().withoutAlias().getSql()));
        in.setRightExpression(new ParenthesedExpressionList<>(
//                deptPair.getValue().stream().map(d -> new JdbcNamedParameter(deptPair.getKey())).toArray(Expression[]::new))
                new JdbcNamedParameter(key)
        ));
        // 追加到 WHERE
        Expression where = select.getWhere();
        if (where != null) {
            select.setWhere(new AndExpression(where, in));
        } else {
            select.setWhere(in);
        }
        ctx.addParam(key, dataPair.getValue());
    }
}